# -*- encoding: utf-8 -*-
"""
File Name: inspect_ring_network_selenium
Description:
Author: 'lirui'
Date: 7/15/2024
Contact: marjey_lee@163.com
Change Activity:
7/15/2024: Converted to use Selenium library
"""
import time
from selenium.webdriver.common.by import By

from ll.modules.spider.selenium_util import SeleniumUtils

_login_url = 'https://cn-km-fdyh-d01.ops.console.ops.topcloud.fdb.com/'
_warning_url = 'https://cn-km-fdyh-d01.ops.console.ops.topcloud.fdb.com/aso/nom/networkOperation/networkOperationCenter'
_username = 'monitor'
_password = 'P#ssw0rd132'
_manager_address = 'aliyun_product_env'


def _login(spider):
    spider.open_browser(_login_url)
    time.sleep(3)
    username_input = spider.find_element(by=By.ID, locator='username')
    username_input.send_keys(_username)
    password_input = spider.find_element(locator='password', by=By.ID, )
    password_input.send_keys(_password)
    login_button = spider.find_element(by=By.ID, locator='button')
    login_button.click()
    return spider


def _load_data(driver):
    driver.navigate_to(_warning_url)
    time.sleep(3)  # 等待页面加载
    tbody = driver.find_element(by=By.TAG_NAME, locator='tbody')
    trs = driver.find_elements_in_element(tbody, by=By.TAG_NAME, locator='tr')

    lines = []
    for tr in trs:
        tds = driver.find_elements_in_element(tr, by=By.TAG_NAME, locator='td')
        line = [td.text for td in tds]
        lines.append(line)

    return lines


def _format_data(data):
    format_data = []
    for d in data:
        if len(d) < 4:
            continue
        latest_occur_time = d[0]
        content = f"{d[2]}_{d[3]}+{d[4]}" if len(d) > 4 else f"{d[2]}_{d[3]}"  # 根据实际情况调整，原代码假设有5个元素，但这里做了兼容处理
        device_source = d[2]
        mapping = {
            'latest_occur_time': latest_occur_time,
            'content': content,
            'device_source': device_source,
            'manager_address': _manager_address
        }
        format_data.append(mapping)
    return format_data


def inspect_aliyun_network():
    spider = SeleniumUtils()
    spider = _login(spider)
    data = _load_data(spider)
    data = _format_data(data)
    spider.close_browser()
    return data


def _main():
    for _ in range(10):
        data = inspect_aliyun_network()
        print(data)


if __name__ == '__main__':
    _main()
